<template>
  <div id="app">
    <div
      class="drag-container"
      @mousedown="startDrag"
      @mousemove="doDrag"
      @mouseup="endDrag"
      @mouseleave="endDrag"
    >
      <div class="drag-selection" :style="selectionStyle"></div>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      dragging: false,
      startX: 0,
      endX: 0,
      containerWidth: 0,
    };
  },
  computed: {
    selectionStyle() {
      if (this.dragging) {
        return {
          width: `${Math.abs(this.endX - this.startX)}px`,
          left: `${Math.min(this.startX, this.endX)}px`,
        };
      }
      return {};
    },
  },
  methods: {
    startDrag(event) {
      this.dragging = true;
      this.startX = event.clientX;
      this.containerWidth = event.target.offsetWidth;
    },
    doDrag(event) {
      if (this.dragging) {
        this.endX = event.clientX;
      }
    },
    endDrag() {
      if (this.dragging) {
        this.dragging = false;
        // 这里可以添加选择后的处理逻辑
      }
    },
  },
  mounted() {
    this.containerWidth = this.$el.querySelector('.drag-container').offsetWidth;
  },
};
</script>
 
<style>
.drag-container {
  position: relative;
  background-color: #ccc;
  width: 500px;
  height: 50px;
  cursor: pointer;
}
 
.drag-selection {
  position: absolute;
  background-color: #09f;
  height: 100%;
}
</style>